package com.azusa.xbiao.utils;

import com.azusa.xbiao.entity.User;
import com.azusa.xbiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 获取登录用户的信息
 */
@Component
public class LoginUserUtil {

    private static RedisTemplate redisTemplate;

    private static HttpSession session;

    private static HttpServletRequest request;

    private static UserService userService;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        LoginUserUtil.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setSession(HttpSession session) {
        LoginUserUtil.session = session;
    }

    @Autowired
    public void setRequest(HttpServletRequest request) {
        LoginUserUtil.request = request;
    }

    @Autowired
    public void setUserService(UserService userService) {
        LoginUserUtil.userService = userService;
    }

    /**
     * 获取当前登录的用户
     *
     * @return
     */
    public static User getLoginUser() {

        /**
         * 从session获取userId
         */
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId != null) {
            User user = (User) redisTemplate.opsForValue().get("loginUser:" + userId);
            if (user == null) {
                user = userService.findUserLookById(userId);
                // 续期
                redisTemplate.opsForValue().set("loginUser:" + userId, user);
            }
            return user;
        }

        /**
         * 从Cookie里面获取
         */
        Cookie cookie = getCookie("userId");

        if (cookie != null) {
            userId = Integer.parseInt(cookie.getValue());
            User user = (User) redisTemplate.opsForValue().get("loginUser:" + userId);
            if (user == null) {
                user = userService.findUserLookById(user.getId());
                redisTemplate.opsForValue().set("loginUser:" + userId, user);
            }
            return user;
        }

        return null;
    }

    /**
     * 根据cookieName获取Cookie
     *
     * @param cookieName
     * @return
     */
    public static Cookie getCookie(String cookieName) {

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie;
                }
            }
        }

        return null;
    }

    /**
     * 获取当前登录用户的id
     *
     * @return
     */
    public static Integer getId() {
        if (getLoginUser() != null) {
            return getLoginUser().getId();
        }
        return null;
    }
}